package org.chen.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.chen.common.vo.ResultVO;
import org.chen.entity.CategoryInfo;
import org.chen.entity.Model;
import org.chen.feign.CategoryClient;
import org.chen.mapper.ModelMapper;
import org.chen.mapper.VoiceMapper;
import org.chen.query.ModelQueryParams;
import org.chen.request.ModelRequest;
import org.chen.request.ModelUpdateRequest;
import org.chen.service.ModelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class ModelServiceImpl extends ServiceImpl<ModelMapper, Model> implements ModelService {

    @Autowired
    private ModelMapper modelMapper;

    @Autowired
    private CategoryClient categoryClient;

    @Autowired
    private VoiceMapper voiceMapper;

    @Override
    public Page<Model> queryModels(ModelQueryParams params) {
        Page<Model> page = new Page<>(params.getPage(), params.getPageSize());

        LambdaQueryWrapper<Model> queryWrapper = new LambdaQueryWrapper<>();

        // 添加标题搜索条件
        if (StringUtils.hasText(params.getName())) {
            queryWrapper.like(Model::getName, params.getName());
        }

        if (StringUtils.hasText(params.getLanguage())) {
            queryWrapper.like(Model::getLanguage, params.getLanguage());
        }

        // 添加分类条件
        if (params.getPrimaryCategoryId() != null) {
            queryWrapper.eq(Model::getPrimaryCategoryId, params.getPrimaryCategoryId());
        }

        if (params.getSecondaryCategoryId() != null) {
            queryWrapper.eq(Model::getSecondaryCategoryId, params.getSecondaryCategoryId());
        }

        if (params.getTertiaryCategoryId() != null) {
            queryWrapper.eq(Model::getTertiaryCategoryId, params.getTertiaryCategoryId());
        }

        // 按创建时间倒序排序
        queryWrapper.orderByDesc(Model::getCreateTime);

        return modelMapper.selectPage(page, queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Model saveModel(ModelRequest modelRequest) {
        List<Long> categoryIds = new ArrayList<>();
        categoryIds.add(modelRequest.getPrimaryCategoryId());
        categoryIds.add(modelRequest.getSecondaryCategoryId());
        // 只有当三级分类ID不为null时才添加到列表
        if (modelRequest.getTertiaryCategoryId() != null) {
            categoryIds.add(modelRequest.getTertiaryCategoryId());
        }

        // 使用Feign调用分类服务，验证分类是否存在
        ResultVO<List<CategoryInfo>> categoriesResult = categoryClient.getCategoriesByIds(categoryIds);

        if (categoriesResult.getCode() != 200 || categoriesResult.getData() == null ||
                categoriesResult.getData().size() != categoryIds.size()) {
            throw new RuntimeException("获取分类信息失败");
        }

        // 将分类集合转换为Map，便于查找
        Map<Long, CategoryInfo> categoryMap = categoriesResult.getData().stream()
                .collect(Collectors.toMap(CategoryInfo::getId, Function.identity()));

        // 获取各个分类
        CategoryInfo primaryCategory = categoryMap.get(modelRequest.getPrimaryCategoryId());
        CategoryInfo secondaryCategory = categoryMap.get(modelRequest.getSecondaryCategoryId());
        CategoryInfo tertiaryCategory = null;
        if (modelRequest.getTertiaryCategoryId() != null) {
            tertiaryCategory = categoryMap.get(modelRequest.getTertiaryCategoryId());
        }

        // 验证必要分类是否存在
        if (primaryCategory == null || secondaryCategory == null) {
            throw new RuntimeException("分类不存在");
        }

        // 验证分类级别是否正确
        if (primaryCategory.getLevel() != 1 || secondaryCategory.getLevel() != 2) {
            throw new RuntimeException("分类级别不正确");
        }

        // 如果有三级分类，验证其级别
        if (tertiaryCategory != null && tertiaryCategory.getLevel() != 3) {
            throw new RuntimeException("三级分类级别不正确");
        }

        // 验证分类关系是否正确
        if (!secondaryCategory.getParentId().equals(primaryCategory.getId())) {
            throw new RuntimeException("一级与二级分类关系不正确");
        }

        // 如果有三级分类，验证与二级分类的关系
        if (tertiaryCategory != null && !tertiaryCategory.getParentId().equals(secondaryCategory.getId())) {
            throw new RuntimeException("二级与三级分类关系不正确");
        }

        Model model = new Model();
        model.setName(modelRequest.getModelName());
        model.setAudioPath(modelRequest.getAudioPath());
        model.setVideoPath(modelRequest.getVideoPath());
        model.setImagePath(modelRequest.getImagePath());
        model.setVoiceId(modelRequest.getVoiceId());
        model.setCreateTime(LocalDateTime.now());
        model.setUpdateTime(LocalDateTime.now());
        model.setPrimaryCategoryId(modelRequest.getPrimaryCategoryId());
        model.setSecondaryCategoryId(modelRequest.getSecondaryCategoryId());
        model.setTertiaryCategoryId(modelRequest.getTertiaryCategoryId());// 可能为null
        model.setPrimaryCategoryName(primaryCategory.getName());
        model.setSecondaryCategoryName(secondaryCategory.getName());

        // 如果有三级分类，设置其名称，否则设置为null
        if (tertiaryCategory != null) {
            model.setTertiaryCategoryName(tertiaryCategory.getName());
        } else {
            model.setTertiaryCategoryName(null);
        }

        model.setLanguage(modelRequest.getLanguage());

        modelMapper.insert(model);

        return model;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Model updateModel(ModelUpdateRequest modelUpdateRequest) {
        // 首先检查模型是否存在
        Model existingModel = getById(modelUpdateRequest.getId());
        if (existingModel == null) {
            throw new RuntimeException("模型不存在");
        }

        List<Long> categoryIds = new ArrayList<>();
        categoryIds.add(modelUpdateRequest.getPrimaryCategoryId());
        categoryIds.add(modelUpdateRequest.getSecondaryCategoryId());
        // 只有当三级分类ID不为null时才添加到列表
        if (modelUpdateRequest.getTertiaryCategoryId() != null) {
            categoryIds.add(modelUpdateRequest.getTertiaryCategoryId());
        }

        // 使用Feign调用分类服务，验证分类是否存在
        ResultVO<List<CategoryInfo>> categoriesResult = categoryClient.getCategoriesByIds(categoryIds);

        if (categoriesResult.getCode() != 200 || categoriesResult.getData() == null ||
                categoriesResult.getData().size() != categoryIds.size()) {
            throw new RuntimeException("获取分类信息失败");
        }

        // 将分类集合转换为Map，便于查找
        Map<Long, CategoryInfo> categoryMap = categoriesResult.getData().stream()
                .collect(Collectors.toMap(CategoryInfo::getId, Function.identity()));

        // 获取各个分类
        CategoryInfo primaryCategory = categoryMap.get(modelUpdateRequest.getPrimaryCategoryId());
        CategoryInfo secondaryCategory = categoryMap.get(modelUpdateRequest.getSecondaryCategoryId());
        CategoryInfo tertiaryCategory = null;
        if (modelUpdateRequest.getTertiaryCategoryId() != null) {
            tertiaryCategory = categoryMap.get(modelUpdateRequest.getTertiaryCategoryId());
        }

        // 验证必要分类是否存在
        if (primaryCategory == null || secondaryCategory == null) {
            throw new RuntimeException("分类不存在");
        }

        // 验证分类级别是否正确
        if (primaryCategory.getLevel() != 1 || secondaryCategory.getLevel() != 2) {
            throw new RuntimeException("分类级别不正确");
        }

        // 如果有三级分类，验证其级别
        if (tertiaryCategory != null && tertiaryCategory.getLevel() != 3) {
            throw new RuntimeException("三级分类级别不正确");
        }

        // 验证分类关系是否正确
        if (!secondaryCategory.getParentId().equals(primaryCategory.getId())) {
            throw new RuntimeException("一级与二级分类关系不正确");
        }

        // 如果有三级分类，验证与二级分类的关系
        if (tertiaryCategory != null && !tertiaryCategory.getParentId().equals(secondaryCategory.getId())) {
            throw new RuntimeException("二级与三级分类关系不正确");
        }

        // 更新模型信息
        existingModel.setName(modelUpdateRequest.getName());
        existingModel.setUpdateTime(LocalDateTime.now());
        existingModel.setPrimaryCategoryId(modelUpdateRequest.getPrimaryCategoryId());
        existingModel.setSecondaryCategoryId(modelUpdateRequest.getSecondaryCategoryId());
        existingModel.setTertiaryCategoryId(modelUpdateRequest.getTertiaryCategoryId());
        existingModel.setPrimaryCategoryName(primaryCategory.getName());
        existingModel.setSecondaryCategoryName(secondaryCategory.getName());

        // 如果有三级分类，设置其名称，否则设置为null
        if (tertiaryCategory != null) {
            existingModel.setTertiaryCategoryName(tertiaryCategory.getName());
        } else {
            existingModel.setTertiaryCategoryName(null);
        }

        modelMapper.updateById(existingModel);

        return existingModel;
    }

    @Override
    public boolean deleteById(Long id) {
        Model model = modelMapper.selectById(id);
        if (model == null) {
            return false;
        }else {
            modelMapper.deleteById(id);
            voiceMapper.deleteById(model.getVoiceId());
            return true;
        }
    }

    @Override
    public Long CountCommon(ModelQueryParams params) {
        LambdaQueryWrapper<Model> queryWrapper = new LambdaQueryWrapper<>();

        // 添加标题搜索条件
        if (StringUtils.hasText(params.getName())) {
            queryWrapper.like(Model::getName, params.getName());
        }

        return modelMapper.selectCount(queryWrapper);
    }
}
